<!-- -->
<template>
  <div class="consumer">
    <el-container>
      <el-header>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          title="批量删除"
          @click="deleteAll()"
        >批量删除</el-button>
        <el-input
          placeholder="请输入用户名称"
          v-model="searchUser"
          class="input-with-select"
          style="width:30%"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            title="点击搜索"
            @click="searchConsumer()"
          ></el-button>
        </el-input>
        <el-button
          type="primary"
          icon="el-icon-plus"
          title="添加用户"
          style="margin-left:14px"
          v-on:click="dialogVisible = true"
          >添加用户</el-button
        >
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
          <el-form
            :label-position="labelPosition"
            label-width="80px"
            :model="addForm"
          >
            <el-form-item label="用户名">
              <el-row>
                <el-col :span="6">
                  <el-input
                    v-model="addForm.username"
                    placeholder="请输入用户名"
                  ></el-input>
                </el-col>
                <el-col :span="2">昵称</el-col>
                <el-col :span="6">
                  <el-input
                    v-model="addForm.nickname"
                    placeholder="请输入昵称"
                  ></el-input>
                </el-col>
                <el-col :span="2">性别</el-col>
                <el-col :span="6">
                  <el-select v-model="addForm.gender" placeholder="请选择性别">
                    <el-option label="男" :value="1"></el-option>
                    <el-option label="女" :value="2"></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="1"
                :show-file-list="false"
                :http-request="UploadImage"
              >
                <img style="height:100px;width:100px;" v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>

              <!-- <el-upload
                class="upload-demo"
                action="1"
                :file-list="fileList"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload> -->
            </el-form-item>
            <el-form-item label="出生日期">
              <!-- <el-date-picker
                v-model="addForm.birthday"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker> -->

              <el-date-picker
                v-model="addForm.birthday"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input
                v-model="addForm.phone"
                placeholder="请填写手机号码"
                type="phone"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input
                v-model="addForm.email"
                placeholder="请填写邮箱"
                type="email"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input
                v-model="addForm.password"
                placeholder="请填写密码"
                type="password"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input
                v-model="addForm.repassword"
                placeholder="请填写密码"
                type="password"
              ></el-input>
            </el-form-item>
            <el-form-item label="简介">
              <el-row>
                <el-col>
                  <el-input
                    type="textarea"
                    v-model="addForm.info"
                    placeholder="请填写用户简介"
                  ></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addConsumer()">确 定</el-button>
          </span>
        </el-dialog>
        <el-button
          type="success"
          icon="el-icon-refresh"
          title="刷新"
          style="margin-left:14px"
          @click="refresh()"
          >刷新</el-button
        >
      </el-header>
      <el-main>
        <div>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <span class="total">共有数据 {{totalSize}} 条</span>
          <template>
            <el-table
              :data="tableData"
              style="width: 100%;margin-top:2%;"
              show-overflow-tooltip="true"
            >
              <el-table-column
                align ="center"
                width = "60">
                <template slot-scope="scope">
                  <el-checkbox-group v-model="checkedId" @change="handleCheckedChange">
                    <el-checkbox :key="scope.row.id" :label="scope.row.id">{{""}}</el-checkbox>
                  </el-checkbox-group>
                </template>
              </el-table-column>
              <el-table-column label="ID" prop="id"></el-table-column>
              <el-table-column label="用户名" prop="username"></el-table-column>
              <el-table-column label="昵称" prop="nickname"></el-table-column>
              <el-table-column label="性别" prop="_gender"></el-table-column>
              <el-table-column
                label="创建时间"
                prop="createTime"
              ></el-table-column>
              <el-table-column label="手机" prop="phone"></el-table-column>
              <el-table-column label="邮箱" prop="email"></el-table-column>
              <el-table-column label="简介" prop="info"></el-table-column>
              <el-table-column label="状态" prop="_status"></el-table-column>
              <el-table-column label="操作" width="260">
                <template slot-scope="scope">
                  <el-button
                  type="primary"
                    size="mini"
                    @click="
                      handleEdit1(scope.$index, scope.row),
                        (dialogVisible1 = true)
                    "
                    >角色赋予</el-button
                  >
                  <el-button
                    size="mini"
                    @click="
                      handleEdit(scope.$index, scope.row),
                        (dialogVisible2 = true)
                    "
                    >修改</el-button
                  >
                  <el-button
                    size="mini"
                    type="danger"
                    @click.native.prevent="
                      handleDelete(scope.$index, scope.row.id)
                    "
                    >删除</el-button
                  >
                  <el-dialog
                    title="赋予角色"
                    :visible.sync="dialogVisible1"
                    width="50%"
                  >
                    <el-form
                      :label-position="labelPosition"
                      label-width="80px"
                      :model="setForm"
                    >
                    
                      <el-form-item label="角色名称">
                        <el-select v-model="setForm.rid">
                    <el-option
                      v-for="item in actorList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                      </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                      <el-button @click="dialogVisible1 = false"
                        >取 消</el-button
                      >
                      <el-button type="primary" @click="sendActor(scope.row.id)"
                        >确 定</el-button
                      >
                    </span>
                  </el-dialog>

                  <el-dialog
                    title="修改用户"
                    :visible.sync="dialogVisible2"
                    width="50%"
                  >
                    <el-form
                      :label-position="labelPosition"
                      label-width="80px"
                      :model="fixForm"
                    >
                      <el-form-item label="用户名">
                        <el-row>
                          <el-col :span="6">
                            <el-input
                              v-model="fixForm.username"
                              placeholder="请输入用户名"
                              auto-complete="on"
                              readonly
                            ></el-input>
                          </el-col>
                          <el-col :span="2">昵称</el-col>
                          <el-col :span="6">
                            <el-input
                              v-model="fixForm.nickname"
                              placeholder="请输入昵称"
                              auto-complete="on"
                            ></el-input>
                          </el-col>
                          <el-col :span="2">性别</el-col>
                          <el-col :span="6">
                            <el-select
                              v-model="fixForm.gender"
                              placeholder="请选择性别"
                              auto-complete="on"
                            >
                              <el-option label="男" :value="1"></el-option>
                              <el-option label="女" :value="2"></el-option>
                            </el-select>
                          </el-col>
                        </el-row>
                      </el-form-item>
                      <el-form-item label="头像">
                        <el-upload
                          class="avatar-uploader"
                          action="1"
                          :show-file-list="false"
                          :http-request="UploadImage"
                        >
                          <img style="height:100px;width:100px;" v-if="imageUrl" :src="imageUrl" class="avatar" />
                          <i
                            v-else
                            class="el-icon-plus avatar-uploader-icon"
                          ></i>
                        </el-upload>

                        <!-- <el-upload
                class="upload-demo"
                action="1"
                :file-list="fileList"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload> -->
                      </el-form-item>
                      <el-form-item label="出生日期">
                        <!-- <el-date-picker
                v-model="addForm.birthday"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker> -->

                        <el-date-picker
                          v-model="fixForm.birthday"
                          type="datetime"
                          placeholder="选择日期时间"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          auto-complete="on"
                        >
                        </el-date-picker>
                      </el-form-item>
                      <el-form-item label="手机号码">
                        <el-input
                          v-model="fixForm.phone"
                          placeholder="请填写手机号码"
                          type="phone"
                          auto-complete="on"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="邮箱">
                        <el-input
                          v-model="fixForm.email"
                          placeholder="请填写邮箱"
                          type="email"
                          auto-complete="on"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="密码">
                        <el-input
                          v-model="fixForm.password"
                          placeholder="请填写密码"
                          type="password"
                          auto-complete="on"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="密码">
                        <el-input
                          v-model="fixForm.repassword"
                          placeholder="请填写密码"
                          type="password"
                          auto-complete="on"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="简介">
                        <el-row>
                          <el-col>
                            <el-input
                              type="textarea"
                              v-model="fixForm.info"
                              placeholder="请填写用户简介"
                              auto-complete="on"
                            ></el-input>
                          </el-col>
                        </el-row>
                      </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                      <el-button @click="dialogVisible2 = false"
                        >取 消</el-button
                      >
                      <el-button type="primary" @click="fixConsumer()"
                        >确 定</el-button
                      >
                    </span>
                  </el-dialog>
                  
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
      </el-main>
      <el-footer>
        <el-button @click="pre" :disabled="preBool">上一页</el-button>
        <el-input
          v-model="pageNum"
          readonly="readonly"
          style="width:60px;"
        ></el-input>
        <el-button @click="add" :disabled="addBool">下一页</el-button>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
export default {
  name: "Consumer",
  data() {
    return {
      searchUser: "",
      select: "",
      dialogVisible: false,
      dialogVisible1: false,
      dialogVisible2: false,
      labelPosition: "right",
      actorList:[],
      // 存储预览图片
      fileList: [],
      imageUrl: "",
      // 添加用户
      addForm: {
        username: "",
        nickname: "",
        gender: "",
        password: "",
        repassword: "",
        birthday: "",
        image: "",
        phone: "",
        email: "",
        info: ""
      },
      tableData: [],
      fixForm: {},
      setForm:{},
      // 分页
      pageNum: 1,
      addBool: false,
      preBool: true,
      pageSize: 10,
      totalPages: "",
      totalSize: "",
      pages: "",
       // 全选
      checkAll: false,
      checkedId: [],
      isIndeterminate: true,
    };
  },
  watch: {
    pageNum: function(Val) {
      if (Val === 1) {
        this.preBool = true;
        this.addBool = false;
      } else if (Val === this.totalPages) {
        this.addBool = true;
        this.preBool = false;
      } else {
        this.preBool = false;
        this.addBool = false;
      }
    }
  },
  created() {
    this.getActorList();
    this.getConsumerList();
  },

  components: {},

  filters: {},

  computed: {},

  methods: {
    handleCheckedChange(value = []) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.tableData.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableData.length;
      console.log(this.checkedId)
    },
    handleCheckAllChange(val) {
      this.checkedId = []
      this.checkAll = val;
      this.isIndeterminate = !val;
      if(this.checkAll) {
        this.tableData.forEach(data => {
          this.checkedId.push(data.id);
        });
      }
      console.log(this.checkedId)
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.fixForm = row;
      this.imageUrl = row.image;
    },
    handleEdit1(index, row) {
      console.log(index, row);
      this.setForm = row;
    },
    handleDelete(index, id) {
      console.log(index, id);
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteConsumer(index, id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 分页用
    // handleSizeChange(val) {
    //   console.log(`每页 ${val} 条`);
    // },
    // handleCurrentChange(val) {
    //   console.log(`当前页: ${val}`);
    // },
    add() {
      if (this.pageNum < this.totalPages) {
        this.pageNum++;
        this.getConsumerList();
      } else {
        this.addBool = true;
      }
    },
    pre() {
      if (this.pageNum > 1) {
        this.pageNum--;
        this.getConsumerList();
      } else {
        this.preBool = true;
      }
    },
    Success(index) {
      this.$message.success(index);
    },
    Fail(index) {
      this.$message.error(index);
    },
    refresh() {
      this.pageNum = 1;
      this.pageSize = 10;
      this.searchUser = "";
      this.getConsumerList();
    },
    UploadImage(param) {
      // console.log(param)
      const formData = new FormData();
      formData.append("file", param.file);
      this.axios
        .post("/api/upload", formData)
        .then(res => {
          // console.log(res);
          if (res.data.code === 200) {
            this.imageUrl = res.data.data;
            console.log(this.imageUrl);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getActorList() {
      this.axios
        .put("/api/role", {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
        .then(res => {
          console.log(res.data);
          if (res.data.code === 200) {
            let list = res.data.data;
            let bufferList = [];
            // this.totalPages = list.totalPages;
            // this.totalSize = list.totalSize;
            // this.pageNum = list.pageNum;
            // this.pageSize = list.pageSize;
            for(let key in list.content){
              let i = new Object();
              i.label = list.content[key].name;
              i.value = list.content[key].id;
              bufferList.push(i);
            }
            this.actorList = bufferList;
          }
        });
    },
    getConsumerList() {
      console.log(this.pageNum, this.pageSize);
      this.axios
        .put("/api/user", {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
        .then(res => {
          console.log(res.data);
          if (res.data.code === 200) {
            let list = res.data.data;
            this.totalPages = list.totalPages;
            this.totalSize = list.totalSize;
            this.pageNum = list.pageNum;
            this.pageSize = list.pageSize;
            for (let i of list.content) {
              if (i.gender === 1) {
                i._gender = "男";
              } else if (i.gender === 2) {
                i._gender = "女";
              } else {
                i._gender = "暂无信息";
              }
              i._status = i.status ? "启用" : "禁用";
              i.nickname = i.nickname ? i.nickname : "暂无信息";
              i.info = i.info ? i.info : "暂无信息";
            }
            this.tableData = list.content;
          }else{
            this.totalPages = 0;
            this.totalSize = 0;
            this.tableData = [];
          }
        });
    },
    addConsumer() {
      this.addForm.image = this.imageUrl;
      if (
        this.addForm.gender === "" ||
        this.addForm.username === "" ||
        this.addForm.password === "" ||
        this.addForm.birthday === "" ||
        this.addForm.image === "" ||
        this.addForm.email === "" ||
        this.addForm.info === ""
      ) {
        this.Fail("信息不全，无法添加");
      } else {
        if (this.addForm.password == this.addForm.repassword) {
          this.axios
            .post("/api/user/findByName", {
              username: this.addForm.username
            })
            .then(res => {
              if (res.data.code === 200) {
                this.Fail("该用户名已存在，请重新输入");
              } else {
                this.dialogVisible = false;
                // console.log({
                //   username: this.addForm.username,
                //   password: this.addForm.password,
                //   email: this.addForm.email,
                //   phone: this.addForm.phone,
                //   nickname: this.addForm.nickname,
                //   gender: this.addForm.gender,
                //   birthday: this.addForm.birthday,
                //   image: this.addForm.image,
                //   info: this.addForm.info
                // });

                this.axios
                  .post("/api/user", {
                    username: this.addForm.username,
                    password: this.addForm.password,
                    email: this.addForm.email,
                    phone: this.addForm.phone,
                    nickname: this.addForm.nickname,
                    gender: this.addForm.gender,
                    birthday: this.addForm.birthday,
                    image: this.addForm.image,
                    info: this.addForm.info
                  })
                  .then(res => {
                    console.log(res.data);
                    if (res.data.code === 200) {
                      this.Success("添加成功");
                      this.getConsumerList();
                    } else {
                      this.Fail("添加失败");
                    }
                  })
                  .catch(error => {
                    console.log(error);
                    this.Fail("添加失败");
                  });
              }
            });
        } else {
          this.Fail("两次密码均不相同，请重新输入");
        }
      }
    },
    fixConsumer() {
      this.fixForm.image = this.imageUrl;
      if (
        this.fixForm.gender === "" ||
        this.fixForm.username === "" ||
        this.fixForm.password === "" ||
        this.fixForm.birthday === "" ||
        this.fixForm.image === "" ||
        this.fixForm.email === "" ||
        this.fixForm.info === ""
      ) {
        this.Fail("信息不全，无法添加");
      } else {
        if (this.fixForm.password == this.fixForm.repassword) {
          this.dialogVisible2 = false;
          console.log({
            id: this.fixForm.id,
            username: this.fixForm.username,
            password: this.fixForm.password,
            email: this.fixForm.email,
            phone: this.fixForm.phone,
            nickname: this.fixForm.nickname,
            gender: this.fixForm.gender,
            birthday: this.fixForm.birthday,
            image: this.fixForm.image,
            info: this.fixForm.info
          });

          this.axios
            .post("/api/user", {
              id: this.fixForm.id,
              username: this.fixForm.username,
              password: this.fixForm.password,
              email: this.fixForm.email,
              phone: this.fixForm.phone,
              nickname: this.fixForm.nickname,
              gender: this.fixForm.gender,
              birthday: this.fixForm.birthday,
              image: this.fixForm.image,
              info: this.fixForm.info
            })
            .then(res => {
              console.log(res.data);
              if (res.data.code === 200) {
                this.Success("修改成功");
                this.getConsumerList();
              } else {
                this.Fail("修改失败");
              }
            })
            .catch(error => {
              console.log(error);
              this.Fail("修改失败");
            });
        } else {
          this.Fail("两次密码均不相同，请重新输入");
        }
      }
    },
    searchConsumer() {
      this.pageNum = 1;
      this.pageSize = 10;
      this.axios
        .put("/api/user", {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          username: this.searchUser
        })
        .then(res => {
          console.log(res.data);
          if (res.data.code === 200) {
            let list = res.data.data;
            this.totalPages = list.totalPages;
            this.totalSize = list.totalSize;
            this.pageNum = list.pageNum;
            this.pageSize = list.pageSize;
            for (let i of list.content) {
              i._gender = i.gender ? "男" : "女";
              i._status = i.status ? "启用" : "禁用";
            }
            this.tableData = list.content;
          }
        });
    },
    deleteConsumer(index, id) {
      this.axios
        .delete("/api/user", {
          params: {
            ids: id
          }
        })
        .then(res => {
          console.log(res.data);
          if (res.data.code === 200) {
            this.Success("删除成功");
            this.tableData.splice(index, 1);
          } else {
            this.Fail("删除失败");
          }
        });
    },
    sendActor(id){
      console.log(id);
      this.axios.post('/api/userRole',{
        uid:id,
        rid:this.setForm.rid
      }).then(res=>{
        console.log(res.data);
        if(res.data.code === 200){
          this.Success("添加成功");
          this.dialogVisible1 = false;
        }
      }).catch(error=>{
        console.log(error);
        
      })
    },
    deleteAll() {
      var data = {
        ids: this.checkedId
      }
      var params = this.qs.stringify(data, { indices: false })
      this.axios.delete('/api/user?'+params
      ).then(response => {
        console.log(response);
        if(response.data.code == 200) {
          this.getConsumerList();
          this.Success("删除成功");
        } else {
          this.Fail("删除失败");
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
};
</script>
<style scoped>
.total {
  font-size: 14px;
  margin-left: 50px;
  color: #606266;
}
.consumer {
  width: 100%;
  height: 100%;
}
.el-container {
  width: 100%;
  height: 100%;
}
.el-header {
  line-height: 60px;
  width: 100%;
}
.el-main {
  width: 100%;
  height: 100%;
  /* background-color: black; */
  overflow-x: hidden;
}
.el-main::-webkit-scrollbar {
  display: none;
}
.el-footer {
  line-height: 60px;
  text-align: right;
}
.searchBar {
  width: 100%;
  height: 5%;
  /* margin-top: 15px; */
}
.el-input {
  width: 93%;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.el-footer {
  text-align: right;
}
</style>